import 'package:flutter/material.dart';

/// 自定义 TabBar
/// 1. 实现 PreferredSizeWidget, 重写 preferredSize
/// 2. 切换 tab 时使用 controller.animateTo() 方法
class MyTabBar extends StatefulWidget implements PreferredSizeWidget {
  final TabController? controller;
  MyTabBar({Key? key, this.controller}) : super(key: key);

  @override
  _MyTabBarState createState() => _MyTabBarState();

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

}

class _MyTabBarState extends State<MyTabBar> {

  int _selectedIndex = 0;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print('didChangeDependencies');
    // 如果使用动画则要使用下面的语句
    // widget.controller!.animation!.addListener(() => setState(() {}));
  }

  _animateTo(int idx) {
    widget.controller!.animateTo(idx);
    setState(() {
      _selectedIndex = idx;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Container(
      color: Colors.white,
      child: SafeArea(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _selectedIndex == 0 ? ElevatedButton(
            onPressed: () {
              _animateTo(0);
            },
            child: Text('今日'),
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20)),
            ),
          ) : TextButton(
            onPressed: () {
              _animateTo(0);
            },
            child: Text('今日'),
          ),
          _selectedIndex == 1 ? ElevatedButton(
            onPressed: () {
              _animateTo(1);
            },
            child: Text('本周'),
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20)),
            ),
          ) : TextButton(
            onPressed: () {
              _animateTo(1);
            },
            child: Text('本周'),
          ),
          _selectedIndex == 2 ? ElevatedButton(
            onPressed: () {
              _animateTo(2);
            },
            child: Text('本月'),
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20)),
            ),
          ) : TextButton(
            onPressed: () {
              _animateTo(2);
            },
            child: Text('本月'),
          ),
        ],
      )),
    );
  }
}
